<template>
  <div ref="chartRef" class="member-bar-chart"></div>
</template>

<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount, watch} from 'vue'
import * as echarts from 'echarts'
import type {MemberBarChartData} from "@/api/statistics/type.ts";

interface Props {
  type: "bar" | 'horizontal'
  data: MemberBarChartData[]
}


const props = defineProps<Props>()

const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const getMemberColor = (index: number) => {
  const colors: Record<number, string> = {
    0: '#4E79A7',
    1: '#F28E2B',
    2: '#E15759',
    3: '#76B7B2',
    4: '#59A14F',
    5: '#EDC948',
    6: '#B07AA1',
    7: '#FF9D00',
    8: '#FFDAC1',
    9: '#FFBE7D'
  }
  return colors[index] || '#B07AA1'
}




const renderChart = () => {
  let index = 0;
  if (!chartRef.value) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: props.type === 'bar' ? 'value' : 'category',
      data: props.type === 'bar' ? undefined : props.data.map((item: MemberBarChartData) => item.name)
    },
    yAxis: {
      type: props.type === 'bar' ? 'category' : 'value',
      data: props.type === 'bar' ? props.data.map((item: MemberBarChartData) => item.name) : undefined,
      axisLabel: {
        interval: 0,
        rotate: props.type === 'horizontal' ? 0 : 0
      }
    },
    series: [
      {
        name: '支出金额',
        type: 'bar',
        data: props.data.map((item: MemberBarChartData) => ({
          value: item.value,
          itemStyle: {
            color: getMemberColor(index++)
          }
        })),
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        },
        label: {
          show: true,
          position: props.type === 'bar' ? 'right' : 'top',
          formatter: '{c}'
        }
      }
    ]
  }

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  renderChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

watch(() => props.type, renderChart)
watch(() => props.data, renderChart, {deep: true})
</script>

<style scoped lang="scss">
.member-bar-chart {
  width: 100%;
  height: 100%;
}
</style>
